My code is :
let obj1 = [
{ city: 'Tokyo', country: 'Japan' },
{ city: 'Bangkok', country: 'Thailand'}
];
function myFunc(arr, key, value){
let newArr = arr.map((e)=>{
let obj = e;
obj[key] = value;
return obj;
})
return newArr
}
console.log(myFunc(obj1, 'continent', 'Asia'));
console.log(obj1);
I don't want to mutate the "obj1" array. That's why I'm using Array.map method. But it still changing the original Array. Does anyone know why this happening? Where I made the mistake?
You could take a new object and spread the old one.
function myFunc(arr, key, value){
return arr.map(e => ({ ...e, [key]: value }));
}
let obj1 = [{ city: 'Tokyo', country: 'Japan' }, { city: 'Bangkok', country: 'Thailand'}];
console.log(myFunc(obj1, 'continent', 'Asia'));
console.log(obj1);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You thought that using the equal operator will copy each object in array so you don't mutate the object
let obj = e;
but what you have in code is another reference to the same item(s) in array.
map itself is not a gurantee you have immutable data structure, you have to correctly copy the data,
for objects in js you can use either Object.assign or the spread operater
let obj = { ...e };
// or
let obj = Object.assign({}, e);